package leetCode.cdj;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class ForkJoinDemo {

    public static void main(String[] args) {
        Long start = System.currentTimeMillis();
        //放入线程池
        ForkJoinPool pool = new ForkJoinPool();
        SumRecursiveTask task = new SumRecursiveTask(1, 9999999999L);
        Long result = pool.invoke(task);
        System.out.println("result="+result);
        Long end = System.currentTimeMillis();
        System.out.println("消耗时间:"+(end-start));
    }
    
//    public static void main(String[] args) {
//        //开始时间
//        Long start = System.currentTimeMillis();
//        long sum = 0l;
//        for (long i = 1; i <= 9999999999L; i++) {
//            sum+=i;
//        }
//        System.out.println(sum);
//        //结束时间
//        Long end = System.currentTimeMillis();
//        System.out.println("消耗时间:"+(end-start));
//    }
}

//1.创建一个求和的任务
//RecursiveTask:表示一个任务
class SumRecursiveTask extends RecursiveTask<Long>{

    //大于3000要拆分(创建一个变量)
    //是否要拆分的临界值
    private static final long THRESHOLD = 3000L;

    //起始值
    private final long start;
    //结束值
    private final long end;

    //构造方法(传递起始值、结束值)
    public SumRecursiveTask(long start, long end) {
        this.start = start;
        this.end = end;
    }

    //任务编写完成
    @Override
    protected Long compute() {
        long length = end - start;
        //计算
        if(length < THRESHOLD){
            long sum = 0;
            for (long i = start; i <= end; i++) {
                sum +=i;
            }
            return sum;
        }else{
            //拆分
        	// fork() 方法 此线程会停下来，分出两个线程，比invokeAll差  https://www.liaoxuefeng.com/article/1146802219354112
            long middle = (start + end) /2;
            SumRecursiveTask left = new SumRecursiveTask(start,middle);
//            left.fork();

            SumRecursiveTask right = new SumRecursiveTask(middle+1,end);
//            right.fork();
            
            invokeAll(left, right);
            return left.join() +right.join();
        }
    }
}